﻿using System.Text.Encodings.Web;
using System.Text.Json;
using Core.Identity.Common.Interfaces.Common.Interfaces;
using Core.Identity.Menus.Dtos;
using Core.Interfaces.Users;
using Core.Models;
using Mapster;
using MediatR;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;

namespace Core.Identity.Menus.Features.Commands.Clone;

/// <summary>
/// 克隆菜单
/// </summary>
public class CloneMenuCommand : IRequest<Result<bool>>
{

}

public class CloneMenuCommandHandler(IIdentityDbContext dbContext) : IRequestHandler<CloneMenuCommand, Result<bool>>
{

    public async Task<Result<bool>> Handle(CloneMenuCommand request, CancellationToken cancellationToken)
    {
        // 1. 查询所有菜单
        var menus = await dbContext.Permissions.ToListAsync(cancellationToken);

        // 2. 序列化为 JSON
        var options = new JsonSerializerOptions
        {
            WriteIndented = true, // 格式化
            DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull,
            Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
        };
        var json = JsonSerializer.Serialize(menus.Adapt<IEnumerable<MenuDto>>(), options);

        // 3. 保存
        var path = Path.Combine(Directory.GetCurrentDirectory());
        Directory.CreateDirectory(path);

        var filePath = Path.Combine(path, "menus.json");
        await File.WriteAllTextAsync(filePath, json, cancellationToken);

        return await Result<bool>.SucceedAsync(true, true, ["克隆成功"]);
    }
}
